package ferp.core.ai.filter;

import ferp.core.ai.tree2.Evaluator;
import ferp.core.card.Card;
import ferp.core.game.Trick;
import ferp.core.player.Hand;

/**
 * User: olegs
 * Date: 2/16/13 4:32 PM
 */
public class FilterWhisterAfterDeclarerMove
{
  public static int apply(Evaluator evaluator, int candidates, int player, int trick, Card.Suit trump, int hand, int declarer)
  {
    int filtered = 0;
    Card lowest = FilterWhisterAfterDeclarerMoveOpen.getLowestBeatCard(evaluator, trick, candidates, player, hand, trump);
    int lowestCandidates = FilterWhisterAfterDeclarerMoveOpen.getLowestCandidates(candidates);

    switch (hand)
    {
      // hand 1 means first move was made by declarer
      case 1:
        if (lowest == null)
          filtered = Hand.add(filtered, lowestCandidates);
        else
        {
          filtered = Hand.add(filtered, lowest.hash);

          // get declarer's card
          Card highest = Trick.highest(trick, trump);

          // add lowest candidates only if rank difference is greater than 1,
          // otherwise partner couldn't have lower beat card than current player
          if (highest.suit != lowest.suit || lowest.rank.ordinal() - highest.rank.ordinal() > 1)
            filtered = Hand.add(filtered, lowestCandidates);
        }

        break;

      case 2:
        byte winner = Trick.winner(trick, trump);

        if (winner == declarer)
          filtered = lowest == null ? Hand.add(filtered, lowestCandidates) : Hand.add(filtered, lowest.hash);
        else
          // the player should not "beat" his partner's card
          filtered = Hand.add(filtered, lowestCandidates);

        break;

    }

    return filtered == 0 ? candidates : filtered;
  }
}
